package auctionhausen



import org.junit.*
import grails.test.mixin.*

@TestFor(ListingController)
@Mock([Customer, Listing, Bid])
class ListingControllerTests {

	def populateValidParams(params) {
		assert params != null

		params["name"] = 'Roger Rabbit Action Figure'
		params["endDate"] = new Date() + 1
		params["startingPrice"] = 35.50
		params["description"] = 'Mint condition! **Like New**'
		params["seller.id"] = 1
	}

	def populateValidCustomerParams(params) {
		assert params != null
		params['email'] ='sanss002@test.umn.edu'
		params['password'] = 'PASSWORD'
	}

	def populateValidBidParams(params) {
		assert params != null

		params["amount"] = 36.00
		params["bidder.id"] = 1
		params["listing"] = [id:1]
	}

	void tearDown() {
		Listing.deleteAll(Listing.getAll())
		Bid.deleteAll(Bid.getAll())
	}

	void testSave() {
		controller.listingService = [createListing : {Map map -> return [hasErrors: {return true}]}, isListingExpired: {}]
		controller.save()

		assert model.listingInstance != null
		assert view == '/listing/create'

		response.reset()

		populateValidParams(params)
		controller.listingService = [createListing : {Map map -> return [hasErrors: {return false}, id: 1]}]
		controller.save()

		assert response.redirectedUrl == '/listing/show/1'
		assert controller.flash.message != null
	}

	// Although this test case isn't passing, the actual functionality
	// as verified through testing in the browser does work correctly.
	// We're seeing a strange Hibernate related exception, and haven't
	// been able to get around it.
	void testAddBid_Success() {
		params.clear()
		populateValidBidParams(params)
		request.method = 'POST'
		
		controller.bidService = [createBid : {Map map -> return [hasErrors: {return false}, amount : params.amount]}]
		controller.addBid()
		assert response.text == "{\"failed\":false,\"expired\":false,\"message\":\"bid.added.message\",\"nextBidAmount\":${params.amount+Bid.MINIMUM_BID_DIFFERENCE}}"
	}

	/*
	 * UI-4: The action of placing a new bid will display a message to the user indicating that the bid was successful (Controller Unit Test)
	 * UI-5: An error message will be displayed if placing a new bid is unsuccessful (Controller Unit Test)
	 */

	void testAddBid_Failure() {
		params.clear()
		populateValidBidParams(params)
		request.method = 'POST'
		
		//test has errors not expired
		controller.listingService = [isListingExpired : {return false}]
		controller.bidService = [createBid: {Map map -> return [hasErrors: {return true}, amount : params.amount]}];
		controller.addBid()
		
		assert  response.text == '{"failed":true,\"expired\":false,"message":"bid.not.added.message"}'
	}
}
